<?php

namespace app\common\model;


use app\common\core\BaseModel;
use think\Db;

/**
 * Class KeywordsModel
 * @package app\admin\model
 */
class KeywordsModel extends BaseModel
{
    protected $autoWriteTimestamp = true;

    protected static $key_groups = [];
    public static function getGroups()
    {
        if (is_null(self::$key_groups)) {
            $group = static::where('group', '<>', '')->distinct(true)->field('group')->select()->all();
            self::$key_groups = array_column($group, 'group');
        }
        return self::$key_groups;
    }

    public static function grow($keyword, $group = '', $isInsert = true)
    {
        $item = Db::name('Keywords')->where('title', $keyword)->find();
        if (!empty($item) && $item['status'] != 1) {
            return false;
        }
        if (empty($item)) {
            if (!$isInsert) return false;
            Db::name('Keywords')->insert([
                'title' => $keyword,
                'group' => $group,
                'v_hot' => 0,
                'hot' => 1,
                'status' => 1,
                'create_time' => time(),
                'update_time' => time()
            ]);
        }
        Db::name('Keywords')->where('title', $keyword)->setInc('hot', 1);
        return true;
    }

    public static function getKeywords($group = '', $limit = 10)
    {
        $model = Db::name('Keywords')->where('status', 1);
        if (!empty($group)) {
            $model->where('group', $group);
        }
        return $model->field('*,v_hot+hot as hotsort')->order('hotsort DESC')->limit($limit)->select();
    }

    /**
     * 内容中的关键字做链接
     * @param string $content 
     * @param array $keywords 预设的关键字，留空将对全部关键字进行链接检测
     * @return string 
     */
    public static function linkKeywrods($content, $keywords = [])
    {
        if (empty($keywords)) {
            $keywords = static::extractKeywords($content);
        }
        return $content;
    }

    /**
     * 从内容中提取关键字
     * @param string $content 
     * @return array 
     */
    public static function extractKeywords($content)
    {
        $keywords = [];

        return $keywords;
    }
}
